package com.lazyboyl.spring.boot.sharding.sphere.proxy.net.handler.factory;

import com.lazyboyl.spring.boot.sharding.sphere.proxy.net.handler.backend.BackendAuthenticator;
import com.lazyboyl.spring.boot.sharding.sphere.proxy.net.handler.backend.BackendConnection;
import com.lazyboyl.spring.boot.sharding.sphere.proxy.net.codec.MySqlPacketDecoder;
import com.lazyboyl.spring.boot.sharding.sphere.proxy.net.handler.backend.BackendHeadHandler;
import com.lazyboyl.spring.boot.sharding.sphere.proxy.net.handler.backend.BackendTailHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

/**
 * @author linzf
 * @since 2021-07-02
 * 类描述： 后端连接的工厂类
 */
public class BackendHandlerFactory extends ChannelInitializer<SocketChannel> {

    private BackendConnectionFactory factory;

    public BackendHandlerFactory(BackendConnectionFactory factory) {
        this.factory = factory;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        BackendConnection connection = factory.getConnection();
        BackendHeadHandler firstHandler = new BackendHeadHandler(connection);
        BackendAuthenticator authHandler = new BackendAuthenticator(connection);
        BackendTailHandler tailHandler = new BackendTailHandler(connection);
        ch.pipeline().addLast(new MySqlPacketDecoder());
        ch.pipeline().addLast("BackendHeadHandler", firstHandler);
        ch.pipeline().addLast(authHandler);
        ch.pipeline().addLast(tailHandler);
    }
}
